package {
	import flash.display.Sprite;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;

	[SWF(width=300,height=200,frameRate=2)]
	public class SocketFPS extends Sprite {
		public function SocketFPS(){
			_socket = new Socket();
			_socket.addEventListener(Event.CONNECT, handler_connect);
			_socket.addEventListener(IOErrorEvent.IO_ERROR, handler_error);
			_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handler_error);
			this.stage.doubleClickEnabled = true;
			this.stage.addEventListener(MouseEvent.CLICK, handler_click);
			this.stage.addEventListener(MouseEvent.DOUBLE_CLICK, handler_doubleClick);
			this.stage.addEventListener(Event.ENTER_FRAME, handler_enterFrame);
			trace('frameRate:', this.stage.frameRate);
		}
		private var _socket:Socket;

		private function handler_error(evt:ErrorEvent):void {
			trace(evt.toString());
		}

		private function handler_connect(evt:Event):void {
			trace('连接成功！');
		}

		//每500毫秒自动发送一次消息，传送false
		private function handler_enterFrame(evt:Event):void {
			send(false);
			trace('enterFrame send');
		}

		//双击切换帧频
		private function handler_doubleClick(evt:MouseEvent):void {
			this.stage.frameRate = (this.stage.frameRate == 2) ? 0 : 2;
		}

		//单击鼠标的时候发送一次消息，传送true
		private function handler_click(evt:MouseEvent):void {
			send(true);
		}

		private function send($value:Boolean):void {
			if (!_socket.connected)
				_socket.connect('127.0.0.1', 3000);
			else {
				_socket.writeBoolean($value);
				_socket.flush();
			}
		}
	}
}